package com.cskaoyan.utils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

public class Md5Utils {
    public static String getMd5(String content) throws Exception {
        //获取信息摘要算法
        MessageDigest messageDigest = MessageDigest.getInstance("md5");
        byte[] contentBytes = content.getBytes();
        byte[] resultBytes = messageDigest.digest(contentBytes);
        StringBuffer buffer = new StringBuffer();
        for (byte resultByte : resultBytes) {
            int temp = resultByte & 0xff;
            String s = Integer.toHexString(temp);
            if (s.length() == 1) {
                buffer.append(0);
            }
            buffer.append(s);
        }
        return buffer.toString();
    }

    public static String getMd5(String content, String salt) throws Exception {
        content = content + "&" + salt + "}";
        return getMd5(content);
    }

    public static String getMultyMd5(File file) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance("md5");
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = fileInputStream.read(bytes, 0, 1024)) != -1){
            messageDigest.update(bytes,0,bytes.length);
        }
        byte[] resultBytes = messageDigest.digest();
        StringBuffer buffer = new StringBuffer();
        for (byte resultByte : resultBytes) {
            int temp = resultByte & 0xff;
            String s = Integer.toHexString(temp);
            if(s.length() == 1) {
                buffer.append(0);
            }
            buffer.append(s);
        }
        return buffer.toString();
    }
}
